//
//  MHBindPhoneViewController.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/6/26.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHBindPhoneViewController.h"
#import "ZLTextField.h"
#import "ZLVerifyCodeButton.h"
#import "MHBindViewModel.h"
// 设置尺寸
#define UI_View_Width   ([UIScreen mainScreen].bounds.size.width) // 屏幕宽度
#define UI_View_Height  ([UIScreen mainScreen].bounds.size.height) // 屏幕高度
#define UI_navBar_Height  64.0 // 导航条高度

// RGB颜色
#define ZLColor(r, g, b)   [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]

@interface MHBindPhoneViewController ()<UITextFieldDelegate>
// 手机号输入框
@property (nonatomic, weak) ZLTextField *mobileField;

// 手机验证码输入框
@property (nonatomic, weak) ZLTextField *codeField;

// 新密码输入框
//@property (nonatomic, weak) ZLTextField *newpswField;

// 确认密码输入框
//@property (nonatomic, weak) ZLTextField *surepswField;

// 获取验证码按钮
@property (nonatomic, weak) ZLVerifyCodeButton *codeBtn;

@property(nonatomic, weak) UIButton *sureButton;

// 验证码
@property (nonatomic, copy) NSString *codeStr;

@property(nonatomic, strong) MHBindViewModel *viewModel;
@end

@implementation MHBindPhoneViewController
@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = ZLColor(243, 243, 243);
    
    [self setupUI];
}

- (void)setupUI {
    
    
//    UILabel *tipsLable = [[UILabel alloc] init];
    
    
    UILabel *tipsLable = [[UILabel alloc] initWithFrame:CGRectMake(0,  UI_navBar_Height + 50 , MH_SCREEN_WIDTH , 30)];
    

    
    CGFloat top = 50;
    CGFloat marginX = 15;
    CGFloat marginH = 40;
    CGFloat textFieldH = 60.0;
    CGFloat codeBtnW = 100;
    
    ZLTextField *mobileField = [[ZLTextField alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(tipsLable.frame) + top, UI_View_Width, textFieldH)];
    mobileField.placeholder = self.viewModel.isModifyFinished ? @"请输入新的手机号码" : @"请填写您的电话号码";
    mobileField.delegate = self;
    mobileField.keyboardType = UIKeyboardTypePhonePad; // 电话号码键盘
    [self.view addSubview:mobileField];
    self.mobileField = mobileField;
    mobileField.textColor = MHMainTextColor;
    
    
    if (self.viewModel.isModify) {
        self.mobileField.text = [MHHTTPService sharedInstance].currentUser.bindPhone;
    }
    [tipsLable setText:self.viewModel.isModify?[NSString stringWithFormat:@"请验证您当前的绑定的手机号为%@****%@",[self.mobileField.text substringToIndex:3],[self.mobileField.text substringFromIndex:self.mobileField.text.length - 4]] : @"为了账户安全，请绑定您常用的手机号码"];
    [tipsLable setFont:[UIFont systemFontOfSize:15.f]];
    tipsLable.textColor = MHAlertTextColor;
    tipsLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:tipsLable];
    
    // 间隔线
    UIView *line = [[UIView alloc] init];
    line.frame = CGRectMake(0, CGRectGetMaxY(mobileField.frame) - 1, MH_SCREEN_WIDTH, 0.5);
    line.backgroundColor = MHTopBottomSpliteLineColor;
    [self.view addSubview:line];
    
    // 手机验证码输入框
    ZLTextField *codeField = [[ZLTextField alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(mobileField.frame), mobileField.width, textFieldH)];
    codeField.placeholder = @"请输入验证码";
    codeField.clearButtonMode = UITextFieldViewModeNever; // 不显示右边清除叉号
    codeField.keyboardType = UIKeyboardTypeNumberPad; // 数字键盘
    codeField.delegate = self;
    codeField.textColor = MHMainTextColor;
    [self.view addSubview:codeField];
    self.codeField = codeField;
    
    // 获取验证码按钮
    ZLVerifyCodeButton *codeBtn = [ZLVerifyCodeButton buttonWithType:UIButtonTypeCustom];
    codeBtn.frame = CGRectMake(codeField.width - codeBtnW - marginX, textFieldH * 0.2, codeBtnW, textFieldH * 0.6 );
    //    codeBtn.centerY = codeField.centerY;
    [codeBtn setTitleColor:MHWhiteTextColor forState:0];
    [codeBtn setTitleColor:MHAlertTextColor forState:UIControlStateDisabled];
    [codeBtn setBackgroundImage:[UIImage imageNamed:@"circle_create_pay"] forState:0];
    [codeBtn setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]] forState:UIControlStateDisabled];
    [codeBtn addTarget:self action:@selector(codeBtnVerification) forControlEvents:UIControlEventTouchUpInside];
    [self.codeField addSubview:codeBtn];
    self.codeBtn = codeBtn;
    
    [codeField addTarget:self
                  action:@selector(textFieldDidChange:)
        forControlEvents:UIControlEventEditingChanged];
    [mobileField addTarget:self
                    action:@selector(textFieldDidChange:)
          forControlEvents:UIControlEventEditingChanged];
    
    if (self.viewModel.isModify) {
        self.codeField.frame = self.mobileField.frame;
        self.mobileField.hidden = YES;
        line.hidden = YES;
    }
    
    // 手机号输入框
    
    // 新密码输入框
//    ZLTextField *newpswField = [[ZLTextField alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(codeField.frame), mobileField.width, textFieldH)];
//    newpswField.placeholder = @"设置新密码";
//    newpswField.secureTextEntry = YES;
//    newpswField.delegate = self;
//    [self.view addSubview:newpswField];
//    self.newpswField = newpswField;
//
//    // 重复新密码输入框
//    ZLTextField *surepswField = [[ZLTextField alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(newpswField.frame), mobileField.width, textFieldH)];
//    surepswField.returnKeyType = UIReturnKeyDone;
//    surepswField.secureTextEntry = YES;
//    surepswField.delegate = self;
//    surepswField.placeholder = @"确认新密码";
//    [self.view addSubview:surepswField];
//    self.surepswField = surepswField;
    
    // 确认按钮
    UIButton *sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sureBtn setTitle:self.viewModel.isModify ? @"下一步": @"绑定" forState:UIControlStateNormal];
//    [sureBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    
    [sureBtn setBackgroundImage:[UIImage imageNamed:@"circle_create_pay"] forState:0];
    [sureBtn setBackgroundImage:[UIImage imageNamed:@"circle_create_pay"] forState:UIControlStateDisabled];
    sureBtn.enabled = (self.codeField.text.length > 0 && self.mobileField.text.length > 0);
    sureBtn.frame = CGRectMake(marginX, MH_SCREEN_HEIGHT - 40 - MH_APPLICATION_TAB_BAR_HEIGHT, 250 , 60);
    sureBtn.titleLabel.font = MHRegularFont_14;
//    sureBtn setTitleColor: forState:<#(UIControlState)#>
    sureBtn.centerX = self.view.centerX;
    [sureBtn addTarget:self action:@selector(sureBtnPress) forControlEvents:UIControlEventTouchUpInside];
//    sureBtn.backgroundColor = ZLColor(251, 0, 7);
    sureBtn.layer.cornerRadius = 3.0;
    sureBtn.clipsToBounds = YES;
    [self.view addSubview:sureBtn];
    [sureBtn setTitleColor:MHWhiteTextColor forState: 0];
    self.sureButton = sureBtn;
//    @weakify(self);
//    [self.sureButton bk_whenTapped:^{
//        @strongify(self);
//
//    }];
    
}



// 调用修改密码接口
- (void)sureBtnPress {
    
    if (![self.mobileField.text isValidateMobile]) {
        [MBProgressHUD mh_showTips:@"请输入正确的手机号"];
        return;
    }
    //绑定手机号
    [[self.viewModel.bindPhoneCommand execute:nil] subscribeNext:^(id x) {
        [MHHTTPService sharedInstance].currentUser.bindPhone = self.viewModel.telephone;
        [MBProgressHUD mh_showTips:@"绑定成功"];
    } error:^(NSError *error) {
        [MBProgressHUD mh_showTips:@"绑定失败"];
    }];
}

// 弹框提示错误信息
- (void)setupAlertMessage:(NSString *)message {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}


-(void) textFieldDidChange:(UITextField *) textField
{
    self.sureButton.enabled = (self.codeField.text.length > 0 && self.mobileField.text.length > 0);
}


// 获取验证码点击事件
- (void)codeBtnVerification {
    
    NSLog(@"验证码:%@", self.mobileField.text);
//    self.codeBtn.enabled  = false;
    if (![self.mobileField.text isValidateMobile]) {
        [MBProgressHUD mh_showTips:@"请输入正确的手机号"];
        return;
    }
    [[self.viewModel.sendVerifyCodeCommand execute:nil] subscribeNext:^(id x) {
        [MBProgressHUD mh_showTips:[NSString stringWithFormat:@"验证码已发送至手机%@****%@",[self.mobileField.text substringToIndex:3],[self.mobileField.text substringFromIndex:self.mobileField.text.length - 4]]];
        [self.codeBtn timeFailBeginFrom:60];
    } error:^(NSError *error) {
        [MBProgressHUD mh_showTips:@"获取失败"];
        [self.codeBtn timeFailBeginFrom:1];
    }];
}

-(void)bindViewModel
{
    [super bindViewModel];
    RAC(self.viewModel , telephone) = [RACSignal merge:@[RACObserve(self.mobileField, text),self.mobileField.rac_textSignal]];
    RAC(self.viewModel , verifyCode) = [RACSignal merge:@[RACObserve(self.codeField, text),self.codeField.rac_textSignal]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark- UITextFieldDelegate

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.mobileField resignFirstResponder];
    [self.codeField resignFirstResponder];
//    [self.newpswField resignFirstResponder];
//    [self.surepswField resignFirstResponder];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.mobileField) {
        [self.mobileField resignFirstResponder];
        [self.codeField becomeFirstResponder];
    } else if (textField == self.codeField) {
        [self.codeField resignFirstResponder];
    }
    
    return YES;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
